import {
  getBisheProjectTagWordCloudUsingGet,
  getClickNumTotalCountUsingGet,
  getTotalCountUsingGet,
} from '@/services/backend/bisheProjectController';
import {
  getTotalCountUsingGet1,
  listOrderInfoVoByPageUsingPost,
} from '@/services/backend/orderInfoController';
import { listAdminUsingPost } from '@/services/backend/userController';
import { WordCloud } from '@ant-design/plots';
import { PageContainer } from '@ant-design/pro-components';
import { history, Link, useModel, useRequest } from '@umijs/max';
import { Avatar, Card, Col, List, message, Row, Skeleton, Statistic, Typography } from 'antd';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { FC, useEffect, useState } from 'react';
import EditableLinkGroup from './components/EditableLinkGroup';
import useStyles from './style.style';

dayjs.extend(relativeTime);

const links = [
  {
    title: '操作一',
    href: '',
  },
  {
    title: '操作二',
    href: '',
  },
  {
    title: '操作三',
    href: '',
  },
];
const PageHeaderContent: FC<{
  currentUser: Partial<API.LoginUserVO>;
}> = ({ currentUser }) => {
  const { styles } = useStyles();
  const loading = currentUser && Object.keys(currentUser).length;
  if (!loading) {
    return (
      <Skeleton
        avatar
        paragraph={{
          rows: 1,
        }}
        active
      />
    );
  }
  return (
    <div className={styles.pageHeaderContent}>
      <div className={styles.avatar}>
        <Avatar size="large" src={currentUser.avatar} />
      </div>
      <div className={styles.content}>
        <div className={styles.contentTitle}>
          早安{currentUser.username}
          ，祝你开心每一天！
        </div>
        <div>{currentUser.profile ?? '这个人很懒,什么也没有留~'}</div>
      </div>
    </div>
  );
};
const ExtraContent: FC<Record<string, any>> = () => {
  const { styles } = useStyles();
  const { data: bisheProjectTotalCount } = useRequest(getTotalCountUsingGet);
  const { data: orderInfoTotalCount } = useRequest(getTotalCountUsingGet1);
  const { data: clickNumTotalCount } = useRequest(getClickNumTotalCountUsingGet);
  return (
    <div className={styles.extraContent}>
      <div className={styles.statItem}>
        <Statistic title="项目总数" value={bisheProjectTotalCount} />
      </div>
      <div className={styles.statItem}>
        <Statistic title="订单总数" value={orderInfoTotalCount} />
      </div>
      <div className={styles.statItem}>
        <Statistic title="项目访问总数" value={clickNumTotalCount} />
      </div>
    </div>
  );
};

type PageType = {
  pageSize: number;
  current: number;
};

const Workplace: FC = () => {
  const { styles } = useStyles();
  //默认页面参数
  const [pageParams, setPageParams] = useState<PageType>({ pageSize: 10, current: 1 });
  const [pageActivities, setActivities] = useState<API.PageOrderInfoVO_>({});
  const [activitiesLoading, setActivitiesLoading] = useState<boolean>(true);
  const { loading: adminLoading, data: adminList = [] } = useRequest(listAdminUsingPost);
  const { loading: wordCloudTagLoading, data: wordCloudTagData } = useRequest(getBisheProjectTagWordCloudUsingGet);
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser ?? {};

  //加载订单信息用来作为activities动态
  const loadOrderInfoVo = async (params?: PageType) => {
    setActivitiesLoading(true);
    try {
      const res = await listOrderInfoVoByPageUsingPost({
        status: 1,
        ...(params ? params : pageParams),
      });
      if (res.code === 0 && res.data) {
        setActivities(res.data);
      }
    } catch (e: any) {
      message.error(e.message);
    } finally {
      setActivitiesLoading(false);
    }
  };

  //初始化
  useEffect(() => {
    loadOrderInfoVo();
  }, []);

  const renderActivities = (item: API.OrderInfoVO) => {
    return (
      <List.Item key={item.id}>
        <List.Item.Meta
          avatar={<Avatar src={item.user?.avatar} />}
          title={
            <span>
              <a className={styles.username}>{item.user?.username}</a>
              &nbsp;
              <span className={styles.event}>
                下单&nbsp;
                {
                  <Typography.Link
                    onClick={() => {
                      if (item.type === 'project') {
                        history.push(`/admin/bisheProject?id=${item.targetId}`);
                      } else if (item.type === 'service') {
                        history.push(`/admin/service?id=${item.targetId}`);
                      }
                    }}
                  >
                    {item.name}
                  </Typography.Link>
                }
                ，共消费&nbsp;{(item?.amount ?? 0) / 100}&nbsp;元-
                {
                  <Typography.Link
                    onClick={() => {
                      history.push(`/admin/orderInfo?id=${item.id}`);
                    }}
                  >
                    订单详情
                  </Typography.Link>
                }
              </span>
            </span>
          }
          description={
            <span className={styles.datetime} title={item.createTime}>
              {dayjs(item.createTime).fromNow()}
            </span>
          }
        />
      </List.Item>
    );
  };

  return (
    <PageContainer
      content={<PageHeaderContent currentUser={currentUser} />}
      extraContent={<ExtraContent />}
    >
      <Row gutter={24}>
        <Col xl={16} lg={24} md={24} sm={24} xs={24}>
          <Card
            styles={{
              body: {
                padding: 0,
              },
            }}
            variant={'borderless'}
            className={styles.activeCard}
            title="动态"
            loading={activitiesLoading}
          >
            <List<API.OrderInfoVO>
              loading={activitiesLoading}
              pagination={{
                total: pageActivities?.total ?? 0,
                current: pageParams.current,
                pageSize: pageParams.pageSize,
                position: 'bottom',
                align: 'end',
                onChange: (page, pageSize) => {
                  setPageParams({ current: page, pageSize: pageSize });
                  loadOrderInfoVo({ pageSize, current: page });
                },
              }}
              renderItem={(item) => renderActivities(item)}
              dataSource={pageActivities?.records ?? []}
              className={styles.activitiesList}
              size="large"
            />
          </Card>
        </Col>
        <Col xl={8} lg={24} md={24} sm={24} xs={24}>
          <Card
            style={{
              marginBottom: 24,
            }}
            title="快速开始 / 便捷导航"
            variant={'borderless'}
            styles={{
              body: { padding: 0 },
            }}
          >
            <EditableLinkGroup
              onAdd={() => {
                message.warning('暂未开放~');
              }}
              links={links}
              linkElement={Link}
            />
          </Card>
          <Card
            style={{
              marginBottom: 24,
            }}
            variant={'borderless'}
            title="热门标签"
            loading={wordCloudTagLoading}
          >
            <div>
              <WordCloud
                height={343}
                data={wordCloudTagData}
                wordField="label"
                weightField="value"
                colorField="name"
                wordStyle={{
                  fontFamily: 'Verdana',
                  fontSize: [12, 60],
                  rotation: 0,
                }}
                random={() => 0.5}
                spiral="rectangular"
                placementStrategy="center"
                padding={0}
              />
            </div>
          </Card>
          <Card
            styles={{
              body: {
                paddingTop: 12,
                paddingBottom: 12,
              },
            }}
            variant={'borderless'}
            title="团队"
            loading={adminLoading}
          >
            <div className={styles.members}>
              <Row gutter={48}>
                {adminList.map((item) => {
                  return (
                    <Col span={12} key={`members-item-${item.id}`}>
                      <a
                        onClick={() => {
                          history.push(`/admin/user?id=${item.id}`);
                        }}
                      >
                        <Avatar src={item.avatar} size="small" />
                        <span className={styles.member}>{item.username}</span>
                      </a>
                    </Col>
                  );
                })}
              </Row>
            </div>
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};
export default Workplace;
